package cn.itcast.nems.student.service.impl;

import cn.itcast.ic.common.exception.v2.BizExceptionProducer;
import cn.itcast.nems.common.account.AccountHolder;
import cn.itcast.nems.common.tenant.TenantInfo;
import cn.itcast.nems.oldems.api.StudentApi;
import cn.itcast.nems.oldems.api.StudentExtendApi;
import cn.itcast.nems.oldems.dto.StudentExtendDto;
import cn.itcast.nems.oldems.vo.StudentAddressListVo;
import cn.itcast.nems.student.bo.StudentAddressEditBo;
import cn.itcast.nems.student.enumeration.StudentErrorBodyEnum;
import cn.itcast.nems.student.service.StudentAddressService;
import cn.itcast.nems.studentrecord.dao.entity.StudentAddress;
import cn.itcast.nems.studentrecord.dao.mapper.E2StudentAddressMapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@Service
@RequiredArgsConstructor
public class StudentAddressServiceImpl implements StudentAddressService {

    private final E2StudentAddressMapper e2StudentAddressMapper;
    private final StudentExtendApi extendApi;
    private final StudentApi studentApi;

    @Override
    public List<StudentAddress> listStudentAddressByStudentId(int studentId) {
        return e2StudentAddressMapper.selectList(
                new QueryWrapper<StudentAddress>()
                        .lambda()
                        .eq(StudentAddress::getStudentId, studentId)
                        .orderByDesc(StudentAddress::getCreatedDatetime)
                        .eq(StudentAddress::getDeletedFlag, false)
        );
    }

    /**
     * 新增学生地址
     *
     * @param bo
     * @return
     */
    @Override
    @Transactional
    public Boolean addStudentAddressInfo(StudentAddressEditBo bo) {
        checkEditAddress(bo);
        var now = LocalDateTime.now();
        var cUser = AccountHolder.getAccount().get();
        var student = studentApi.findById(bo.getStudentId());
        var extend = extendApi.findById(bo.getStudentId());
        // 若为MAIN，则会出现两种情况
        // 1. 存在主要地址，更新主表，并将主表的地址新增一条
        // 2. 不存在主要地址，直接更新主表
        if (bo.getMain() != null && bo.getMain()) {
            // 替换学生，并且新增一条
//            studentMapper.update(
//                    null,
//                    new UpdateWrapper<Student>()
//                            .lambda()
//                            .eq(Student::getId, student.getId())
//                            .set(Student::getCurrentaddress, bo.getAddress())
//            );
            studentApi.setStudentCurrentAddress(
                    bo.getStudentId(),
                    bo.getAddress()
            );
            if (extend != null) {
//                extendMapper.update(
//                        null,
//                        new UpdateWrapper<StudentExtend>()
//                                .lambda()
//                                .eq(StudentExtend::getId, extend.getId())
//                                .set(StudentExtend::getLivingProvince, bo.getProvince())
//                                .set(StudentExtend::getLivingCity, bo.getCity())
//                );
                var dto = new StudentExtendDto();
                dto.setId(bo.getStudentId());
                dto.setLivingProvince(bo.getProvince());
                dto.setLivingCity(bo.getCity());
                dto.setCurrentStatus(extend.getCurrentStatus());
                dto.setJobIntention(extend.getJobIntention());
                dto.setStatus(extend.getStatus());
                extendApi.saveOrUpdate(dto);
                ///
                bo.setAddress(student.getCurrentaddress());
                bo.setProvince(extend.getLivingProvince());
                bo.setCity(extend.getLivingCity());
            } else {
//                extend = new StudentExtend();
//                extend.setId(bo.getStudentId());
//                extend.setLivingProvince(bo.getProvince());
//                extend.setLivingCity(bo.getCity());
//                extend.setCurrentStatus("UNKNOW");
//                extend.setJobIntention("UNKNOW");
//                extend.setStatus(0);
//                extendMapper.insert(extend);
                var dto = new StudentExtendDto();
                dto.setId(bo.getStudentId());
                dto.setLivingProvince(bo.getProvince());
                dto.setLivingCity(bo.getCity());
                dto.setCurrentStatus("UNKNOW");
                dto.setJobIntention("UNKNOW");
                dto.setStatus(0);
                extendApi.saveOrUpdate(dto);
                ///
                bo.setAddress("");
                bo.setProvince("");
                bo.setCity("");
            }
            // 主表之前不存在地址，忽略新增
            if (
                    !StringUtils.hasText(bo.getAddress())
                            || !StringUtils.hasText(bo.getProvince())
                            || !StringUtils.hasText(bo.getCity())
            ) {
                return Boolean.TRUE;
            }
        }
        // 直接新增一条
        StudentAddress address = new StudentAddress();
        address.setStudentId(bo.getStudentId());
        address.setAddress(bo.getAddress());
        address.setCity(bo.getCity());
        address.setProvince(bo.getProvince());
        address.setTenantId(TenantInfo.DEFAULT_TENANT_ID);
        address.setSubtenantId(TenantInfo.DEFAULT_SUBTENANT_ID);
        address.setCreatedBy(cUser);
        address.setCreatedDatetime(now);
        address.setModifiedBy(cUser);
        address.setModifiedDatetime(now);
        address.setDeletedFlag(Boolean.FALSE);
        e2StudentAddressMapper.insert(address);
        return Boolean.TRUE;
    }

    /**
     * 编辑学生地址
     *
     * @param bo
     * @return
     */
    @Override
    @Transactional
    public Boolean editStudentAddressInfo(StudentAddressEditBo bo) {
        checkEditAddress(bo);
        var now = LocalDateTime.now();
        var cUser = AccountHolder.getAccount().get();
        // 编辑
        // 1. 可能将任意地址更新为主要地址
        // 2. 可能只更新主要地址
        // 3. 可能只更新非主要地址
        if (bo.getMain() != null && bo.getMain()) {
            var student = studentApi.findById(bo.getStudentId());
//            studentMapper.update(
//                    null,
//                    new UpdateWrapper<Student>()
//                            .lambda()
//                            .eq(Student::getId, student.getId())
//                            .set(Student::getCurrentaddress, bo.getAddress())
//            );
            studentApi.setStudentCurrentAddress(
                    bo.getStudentId(),
                    bo.getAddress()
            );
            var extend = extendApi.findById(bo.getStudentId());
            if (extend != null) {
//                extendMapper.update(
//                        null,
//                        new UpdateWrapper<StudentExtend>()
//                                .lambda()
//                                .eq(StudentExtend::getId, extend.getId())
//                                .set(StudentExtend::getLivingProvince, bo.getProvince())
//                                .set(StudentExtend::getLivingCity, bo.getCity())
//                );
                var dto = new StudentExtendDto();
                dto.setId(bo.getStudentId());
                dto.setLivingProvince(bo.getProvince());
                dto.setLivingCity(bo.getCity());
                dto.setCurrentStatus(extend.getCurrentStatus());
                dto.setJobIntention(extend.getJobIntention());
                dto.setStatus(extend.getStatus());
                extendApi.saveOrUpdate(dto);
                ///
                bo.setAddress(student.getCurrentaddress());
                bo.setProvince(extend.getLivingProvince());
                bo.setCity(extend.getLivingCity());
            } else {
//                var extend = new StudentExtend();
//                extend.setId(bo.getStudentId());
//                extend.setLivingProvince(bo.getProvince());
//                extend.setLivingCity(bo.getCity());
//                extend.setCurrentStatus("UNKNOW");
//                extend.setJobIntention("UNKNOW");
//                extend.setStatus(0);
//                extendMapper.insert(extend);
                var dto = new StudentExtendDto();
                dto.setId(bo.getStudentId());
                dto.setLivingProvince(bo.getProvince());
                dto.setLivingCity(bo.getCity());
                dto.setCurrentStatus("UNKNOW");
                dto.setJobIntention("UNKNOW");
                dto.setStatus(0);
                extendApi.saveOrUpdate(dto);
                ///
                bo.setAddress(null);
                bo.setProvince(null);
                bo.setCity(null);
            }
            // ID为0，说明意图只为了更新主表，可以直接忽略接下来的操作
            if (bo.getAddressId() == null || bo.getAddressId() == 0) return Boolean.TRUE;
            // 如果不是编辑主角表，需要新增一条
        }
        // 修改附表信息
        e2StudentAddressMapper.update(
                null,
                new UpdateWrapper<StudentAddress>()
                        .lambda()
                        .eq(StudentAddress::getId, bo.getAddressId())
                        .set(StudentAddress::getProvince, bo.getProvince())
                        .set(StudentAddress::getCity, bo.getCity())
                        .set(StudentAddress::getAddress, bo.getAddress())
                        .set(StudentAddress::getModifiedBy, cUser)
                        .set(StudentAddress::getModifiedDatetime, now)
        );
        return Boolean.TRUE;
    }

    /**
     * 删除学生地址
     *
     * @param bo
     * @return
     */
    @Override
    @Transactional
    public Boolean deleteStudentAddressInfo(StudentAddressEditBo bo) {
        var now = LocalDateTime.now();
        var cUser = AccountHolder.getAccount().get();
        if (bo.getAddressId() == null || bo.getAddressId() == 0) {
            BizExceptionProducer.throwProduce(StudentErrorBodyEnum.CURRENT_ADDRESS_NOT_CAN_DELETE);
        }
        e2StudentAddressMapper.update(
                null,
                new UpdateWrapper<StudentAddress>()
                        .lambda()
                        .eq(StudentAddress::getId, bo.getAddressId())
                        .set(StudentAddress::getDeletedFlag, Boolean.TRUE)
                        .set(StudentAddress::getDeletedBy, cUser)
                        .set(StudentAddress::getDeletedDatetime, now)
                        .set(StudentAddress::getDeletedFlag, Boolean.TRUE)
        );
        return Boolean.TRUE;
    }

    @Override
    public List<StudentAddressListVo> listAll(int studentId) {
        var list = new ArrayList<StudentAddressListVo>();
        var main = mainAddress(studentId);
        if (main != null) {
            list.add(main);
        }
        list.addAll(
                listStudentAddressByStudentId(studentId)
                        .stream()
                        .map(this::mapToVo)
                        .toList()
        );
        list.forEach(address -> {
            if (StringUtils.hasText(address.getAddress())) {
                if (address.getAddress().length() > 10) {
                    address.setAddress(address.getAddress().substring(0, 10) + "***");
                }
            }
        });
        return list;
    }

    /**
     * 获取主要地址，若不存在则不显示，固返回null
     *
     * @param studentId
     * @return
     */
    private StudentAddressListVo mainAddress(int studentId) {
        var student = studentApi.findById(studentId);
        var extend = extendApi.findById(studentId);
        if (
                extend != null &&
                        StringUtils.hasText(student.getCurrentaddress())
                        && StringUtils.hasText(extend.getLivingProvince())
                        && StringUtils.hasText(extend.getLivingCity())
        ) {
            StudentAddressListVo vo = new StudentAddressListVo();
            vo.setId(0);
            vo.setProvince(extend.getLivingProvince());
            vo.setCity(extend.getLivingCity());
            vo.setAddress(student.getCurrentaddress());
            vo.setMain(Boolean.TRUE);
            return vo;
        }
        return null;
    }

    /**
     * 将实体转换为VO
     *
     * @param en
     * @return
     */
    private StudentAddressListVo mapToVo(StudentAddress en) {
        if (en == null) {
            return null;
        }
        StudentAddressListVo vo = new StudentAddressListVo();
        vo.setProvince(en.getProvince());
        vo.setCity(en.getCity());
        vo.setAddress(en.getAddress());
        vo.setId(en.getId());
        vo.setMain(Boolean.FALSE);
        return vo;
    }

    private void checkEditAddress(StudentAddressEditBo bo) {
        Assert.isTrue(StringUtils.hasText(bo.getAddress()), "请填写地址");
        Assert.isTrue(bo.getAddress().length() <= 100, "地址长度不能超过100");
    }

}
